package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONObject
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: 项目Token相关统一管理接口* @author: LJT*
 *
 */

public class apiGetToken implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiGetToken.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            return "Request Not Allow!";
        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        String dataSourceID = "dataSource";
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        JSONObject result = new JSONObject();
        JSONObject datatoken = new JSONObject();

        String API_ID = "";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            API_ID = KHUtil.FastJsonNull(request.getParameter("appid"));
            log.debug("原始Get请求参数:" + API_ID);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                API_ID += line;
            }
            log.debug("原始Post请求参数:" + API_ID);
        }
        API_ID = KHUtil.isNull(API_ID) ? "NGS" : API_ID;
        log.debug("API_ID请求参数结果:" + API_ID);

        try {
            // 检查当前Token状态
            String selectSQL = "Select top 1 Token, Expired From KH_Accesstoken Where Api_Id = ? And Del_Flag = 0 And DATEADD(SECOND, isnull(EXPIRED,7200), Createdtime) > GETDATE() order by Createdtime desc";
            List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, API_ID);
            if (selectExits.size() > 0) {
                Map selectExitsm = selectExits.get(0);
                String TOKEN = selectExitsm.get("TOKEN");
                Long EXPIRED = Long.parseLong(selectExitsm.get("EXPIRED").toString());

                result.put("code", 1);
                result.put("msg", "查询完成");
                datatoken.put("access_token", TOKEN);
                datatoken.put("expires_in", EXPIRED);
                result.put("data", datatoken);

            } else {
                if (API_ID == "FAX") {
                    Map<String, String> tokenMap = getFAXToken(eliteBean);
                    String TOKEN = tokenMap.get("access_token");
                    Long EXPIRED = Long.parseLong(tokenMap.get("expires_in").toString());

                    // 清理超长时间的Token
                    String dealSQL = "Delete From KH_Accesstoken Where Createdtime < DATEADD(day, -1, GETDATE()) And Api_Id = ?";
                    jt.update(dealSQL, API_ID);

                    // 标识近期内Token无效
                    dealSQL = "Update KH_Accesstoken Set Del_Flag = 1 Where Del_Flag = 0 And Api_Id = ?";
                    jt.update(dealSQL, API_ID);

                    // 将新获取的Token入库存储
                    dealSQL = "Insert Into Kh_Accesstoken (Rec_Id, Token, Createdtime, Expired, Del_Flag, Api_Id) Values (NEWID(), ?, GETDATE(), ?, 0, ?)";
                    jt.update(dealSQL, TOKEN, EXPIRED, API_ID);

                    result.put("code", 1);
                    result.put("msg", "更新完成");
                    datatoken.put("access_token", TOKEN);
                    datatoken.put("expires_in", EXPIRED);
                    result.put("data", datatoken);
                } else {
                    log.warn("获取Token类型不支持");
                    result.put("code", -2);
                    result.put("msg", "获取Token类型不支持");
                    result.put("data", datatoken);
                }

            }

        } catch (Exception e) {
            log.error("接口处理异常", e);
            // 失败返回

            result.put("code", -1);
            result.put("msg", e.getMessage());
            result.put("data", datatoken);

        }

        log.debug("Token处理完成返回结果:" + result.toString());

        return result.toString();
    }

    // 获取接口Token
    public static Map<String, String> getFAXToken(EliteBean eliteBean) {

        Map<String, String> tokenMap = new HashMap<String, String>();

        Map<String, String> headParams = new HashMap<String, String>();
        headParams.put("Content-Type", "application/x-www-form-urlencoded");

        Map<String, String> callParams = new HashMap<String, String>();
        callParams.put("username", KHDBConfig.getParam(eliteBean, "FAXUSR"));
        callParams.put("password", KHDBConfig.getParam(eliteBean, "FAXPWD"));

        String callBody = KHUtil.urlencode(callParams, "");
        String tokenResult = Util.doHttpPostUseHead(KHDBConfig.getAPIURL(eliteBean, "FAX-loginURL"), callBody, "UTF-8", 120000, 0, headParams);
        log.debug("传真-获取接口Token【tokenResult】:" + tokenResult);

        net.sf.json.JSONObject tokenJson = net.sf.json.JSONObject.fromObject(tokenResult);
        int code = tokenJson.getInt("code");

        if (code == 0) {
            String access_token = tokenJson.getJSONObject("data").getString("token");
            tokenMap.put("access_token", access_token);
            tokenMap.put("expires_in", "1");
        }
        log.debug("传真-获取接口Token【access_token】:" + tokenMap.toString());
        return tokenMap;
    }

    // 获取5G短信接口Token
    public static Map<String, String> get5GSMSToken(EliteBean eliteBean) {

        String getTokenURL = KHDBConfig.getAPIURL(eliteBean, "5GSMS-serverRoot");
        String appId = KHDBConfig.getParam(eliteBean, "5GSMS-appId");// Client ID
        String appSecret = KHDBConfig.getParam(eliteBean, "5GSMS-appSecret");// 密钥

        // 查出传真发送的地址
        Map<String, String> headParams = new HashMap<String, String>();
        headParams.put("Content-Type", "application/json");

        net.sf.json.JSONObject postJson = new net.sf.json.JSONObject();
        postJson.put("client_id", appId);
        postJson.put("client_secret", appSecret);
        postJson.put("grant_type", "client_credentials");

        String resultInfo = Util.doHttpPostUseHead(getTokenURL, postJson.toString(), "UTF-8", 120000, 0, headParams);

        JSONObject resultJson = new JSONObject(resultInfo);

        int code = resultJson.getInt("code");
        Map<String, String> tokenMap = new HashMap<String, String>();

        if (code == 200) {
            String access_token = resultJson.getJSONObject("data").getString("access_token");
            String expires_in = resultJson.getJSONObject("data").getString("expires_in");
            tokenMap.put("access_token", access_token);
            tokenMap.put("expires_in", expires_in);
        }
        log.debug("5G短信-获取接口Token【access_token】:" + tokenMap.toString());
        return tokenMap;
    }
}
